/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include "KmcEncrypt.h"
#include "kmcv3_src/kmcv3.h"
#include "log/Log.h"
#include "system/System.hpp"

namespace {
    const std::string CUR_MODULE_NAME = "NasKmcClient";
}

int KmcEncrypt::Encrypt(const std::string &plainText, std::string &cipherText)
{
    HCP_Log(DEBUG, CUR_MODULE_NAME) << "Enter Encrypt."  << HCPENDLOG;
    char *enPassWord = nullptr;
    if (EncryptV3c(KMC_DOMAIN::KMC_SHARE_INNER_DOMAIN, plainText.c_str(), &enPassWord) != KMC_RET::KMC_SUCESS) {
        HCP_Log(ERR, CUR_MODULE_NAME) << "Encrypt failed." << HCPENDLOG;
        return Module::FAILED;
    }
    if (enPassWord != nullptr) {
        cipherText = enPassWord;
        uint64_t len = cipherText.length();
        memset_s(enPassWord, len, 0, len);
    }
    if (cipherText.empty()) {
        HCP_Log(ERR, CUR_MODULE_NAME) << "CipherText is empty string." << HCPENDLOG;
        return Module::FAILED;
    }
    KmcFree(enPassWord);
    HCP_Log(DEBUG, CUR_MODULE_NAME) << "Finish Encrypt."  << HCPENDLOG;
    return Module::SUCCESS;
}

int KmcEncrypt::Decrypt(std::string &plainText, const std::string &cipherText)
{
    HCP_Log(DEBUG, CUR_MODULE_NAME) << "Enter Decrypt."  << HCPENDLOG;
    char *keyData = nullptr;
    if (DecryptV3c(KMC_DOMAIN::KMC_SHARE_INNER_DOMAIN, &keyData, cipherText.c_str()) != KMC_RET::KMC_SUCESS) {
        HCP_Log(ERR, CUR_MODULE_NAME) << "Decrypt failed." << HCPENDLOG;
        return Module::FAILED;
    }
    if (keyData != nullptr) {
        plainText = keyData;
        uint64_t len = plainText.length();
        memset_s(keyData, len, 0, len);
    }
    if (plainText.empty()) {
        HCP_Log(ERR, CUR_MODULE_NAME) << "PlainText is empty string." << HCPENDLOG;
        return Module::FAILED;
    }
    KmcFree(keyData);
    keyData = nullptr;
    HCP_Log(DEBUG, CUR_MODULE_NAME) << "Finish Decrypt."  << HCPENDLOG;
    return Module::SUCCESS;
}
